<template>
  <div class="task-management">
    <h1 class="page-title">任务管理</h1>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-filter">
        <input
          type="text"
          v-model="searchKeyword"
          placeholder="搜索任务名称或描述"
          class="form-input search-input"
          @keyup.enter="getTasks"
        />
        <select v-model="filterStatus" class="form-select" @change="getTasks">
          <option value="">全部状态</option>
          <option value="draft">草稿</option>
          <option value="scheduled">已计划</option>
          <option value="in_progress">进行中</option>
          <option value="paused">已暂停</option>
          <option value="completed">已完成</option>
          <option value="cancelled">已取消</option>
          <option value="failed">已失败</option>
        </select>
        <select v-model="filterPriority" class="form-select" @change="getTasks">
          <option value="">全部优先级</option>
          <option value="normal">普通</option>
          <option value="urgent">紧急</option>
        </select>
      </div>
      <button class="btn btn-primary" @click="openCreateDialog">
        创建任务
      </button>
    </div>

    <!-- 任务列表 -->
    <div class="task-list">
      <el-table :data="tasks" border style="width: 100%">
        <el-table-column prop="name" label="任务名称" width="180" />
        <el-table-column prop="priority" label="优先级" width="120">
          <template #default="scope">
            <span :class="['priority-tag', scope.row.priority]">
              {{ scope.row.priority === "urgent" ? "紧急" : "普通" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="responsible_person" label="负责人" width="100">
          <template #default="scope">
            <span :class="['priority-tag', scope.row.priority]">
              {{ scope.row.responsible_person?.username || "-" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <span :class="['status-tag', scope.row.status]">
              {{ getStatusText(scope.row.status) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="scope">
            <el-progress :percentage="scope.row.progress" />
          </template>
        </el-table-column>
        <el-table-column prop="execute_type" label="执行类型" width="120">
          <template #default="scope">
            <span>
              {{
                scope.row.execute_type === "immediate"
                  ? "立即执行"
                  : scope.row.execute_type === "manual"
                  ? "手动启动"
                  : "定时执行"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="scheduled_time" label="计划时间" width="180">
          <template #default="scope">
            <span>
              {{
                scope.row.scheduled_time
                  ? formatDate(scope.row.scheduled_time)
                  : "-"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column prop="action" label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="info" @click="viewTask(scope.row.id)" size="small"
              >查看</el-button
            >
            <el-button
              type="primary"
              @click="editTask(scope.row)"
              size="small"
              v-if="
                scope.row.status !== 'completed' &&
                scope.row.status !== 'cancelled' &&
                scope.row.status !== 'failed'
              "
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="deleteTask(scope.row.id)"
              size="small"
              v-if="
                scope.row.status === 'draft' || scope.row.status === 'cancelled'
              "
              >删除</el-button
            >
            <el-button
              type="success"
              size="small"
              @click="updateTaskStatus(scope.row.id, 'in_progress')"
              v-if="
                scope.row.status === 'scheduled' ||
                scope.row.status === 'pending'
              "
              >开始</el-button
            >
            <el-button
              type="warning"
              size="small"
              @click="updateTaskStatus(scope.row.id, 'paused')"
              v-if="scope.row.status === 'in_progress'"
              >暂停</el-button
            >
            <el-button
              type="info"
              size="small"
              @click="updateTaskStatus(scope.row.id, 'in_progress')"
              v-if="scope.row.status === 'paused'"
              >继续</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <button
          class="btn btn-sm"
          @click="changePage(1)"
          :disabled="page === 1"
        >
          首页
        </button>
        <button
          class="btn btn-sm"
          @click="changePage(page - 1)"
          :disabled="page === 1"
        >
          上一页
        </button>
        <span>第 {{ page }} 页 / 共 {{ totalPages }} 页</span>
        <button
          class="btn btn-sm"
          @click="changePage(page + 1)"
          :disabled="page >= totalPages"
        >
          下一页
        </button>
        <button
          class="btn btn-sm"
          @click="changePage(totalPages)"
          :disabled="page >= totalPages"
        >
          末页
        </button>
      </div>
    </div>

    <!-- 任务详情对话框 -->
    <el-dialog
      class="dialog"
      v-model="showDetailDialog"
      width="800"
      title="任务详情"
      top="50px"
    >
      <div class="dialog-content">
        <div class="detail-section">
          <h3>基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>任务名称：</label>
              <span>{{ currentTask.name }}</span>
            </div>
            <div class="info-item">
              <label>描述：</label>
              <span>{{ currentTask.description || "-" }}</span>
            </div>
            <div class="info-item">
              <label>优先级：</label>
              <span class="priority-tag" :class="currentTask.priority">
                {{ currentTask.priority === "urgent" ? "紧急" : "普通" }}
              </span>
            </div>
            <div class="info-item">
              <label>负责人：</label>
              <span>{{
                currentTask.responsible_person
                  ? currentTask.responsible_person.username
                  : "-"
              }}</span>
            </div>
            <div class="info-item">
              <label>执行类型：</label>
              <span>{{ getExecuteTypeText(currentTask.execute_type) }}</span>
            </div>
            <div class="info-item">
              <label>计划时间：</label>
              <span>{{
                currentTask.scheduled_time
                  ? formatDate(currentTask.scheduled_time)
                  : "-"
              }}</span>
            </div>
            <div class="info-item">
              <label>状态：</label>
              <span class="status-tag" :class="currentTask.status">
                {{ getStatusText(currentTask.status) }}
              </span>
            </div>
            <div class="info-item">
              <label>进度：</label>
              <div class="progress-wrapper">
                <div class="progress-bar">
                  <div
                    class="progress-fill"
                    :style="{ width: currentTask.progress + '%' }"
                  ></div>
                </div>
                <span class="progress-text">{{ currentTask.progress }}%</span>
              </div>
            </div>
            <div class="info-item">
              <label>开始时间：</label>
              <span>{{
                currentTask.start_time
                  ? formatDate(currentTask.start_time)
                  : "-"
              }}</span>
            </div>
            <div class="info-item">
              <label>结束时间：</label>
              <span>{{
                currentTask.end_time ? formatDate(currentTask.end_time) : "-"
              }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h3>关联配置</h3>

          <div class="subsection">
            <h4>关联航线</h4>
            <table
              class="mini-table"
              v-if="
                currentTask.task_routes && currentTask.task_routes.length > 0
              "
            >
              <thead>
                <tr>
                  <th>序号</th>
                  <th>航线名称</th>
                  <th>描述</th>
                  <th>预计时间</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(taskRoute, index) in sortedTaskRoutes"
                  :key="taskRoute.id"
                >
                  <td>{{ taskRoute.order_index + 1 }}</td>
                  <td>{{ taskRoute.route ? taskRoute.route.name : "-" }}</td>
                  <td>
                    {{
                      taskRoute.route ? taskRoute.route.description || "-" : "-"
                    }}
                  </td>
                  <td>
                    {{
                      taskRoute.route
                        ? taskRoute.route.estimated_time + "分钟"
                        : "-"
                    }}
                  </td>
                </tr>
              </tbody>
            </table>
            <p v-else>未关联航线</p>
          </div>

          <div class="subsection">
            <h4>检测模型</h4>
            <div
              class="model-list"
              v-if="
                currentTask.detection_model_ids &&
                currentTask.detection_model_ids.length > 0
              "
            >
              <span
                v-for="modelId in currentTask.detection_model_ids"
                :key="modelId"
                class="model-tag"
              >
                模型 {{ modelId }}
              </span>
            </div>
            <p v-else>未关联检测模型</p>
          </div>

          <div class="subsection">
            <h4>触发条件</h4>
            <div
              class="condition-list"
              v-if="
                currentTask.trigger_conditions &&
                currentTask.trigger_conditions.length > 0
              "
            >
              <div
                v-for="(condition, index) in currentTask.trigger_conditions"
                :key="index"
                class="condition-item"
              >
                <strong>{{ getTriggerTypeText(condition.type) }}：</strong>
                <span>{{ formatTriggerParams(condition) }}</span>
              </div>
            </div>
            <p v-else>未设置触发条件</p>
          </div>
        </div>

        <div class="detail-section">
          <h3>异常策略</h3>
          <div
            class="strategy-list"
            v-if="
              currentTask.exception_strategies &&
              currentTask.exception_strategies.length > 0
            "
          >
            <div
              v-for="(strategy, index) in currentTask.exception_strategies"
              :key="index"
              class="strategy-item"
            >
              <div class="strategy-header">
                <strong>{{ getExceptionTypeText(strategy.type) }}</strong>
                <span class="strategy-action">{{
                  getActionText(strategy.action)
                }}</span>
              </div>
              <div
                class="strategy-params"
                v-if="Object.keys(strategy.params).length > 0"
              >
                <div
                  v-for="(value, key) in strategy.params"
                  :key="key"
                  class="param-item"
                >
                  <span>{{ formatParamKey(key) }}: {{ value }}</span>
                </div>
              </div>
            </div>
          </div>
          <p v-else>未设置异常策略</p>
        </div>
      </div>
    </el-dialog>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      class="dialog"
      v-model="showDialog"
      width="800"
      :title="isEditMode ? '编辑任务' : '创建任务'"
      top="50px"
    >
      <div class="dialog-content">
        <div class="dialog-body">
          <form @submit.prevent="submitTask">
            <!-- 基本信息 -->
            <div class="form-section">
              <h3>基本信息</h3>
              <div class="form-row">
                <div class="form-group">
                  <label>任务名称 *</label>
                  <input
                    type="text"
                    v-model="formData.name"
                    class="form-input"
                    required
                    placeholder="请输入任务名称"
                  />
                </div>
                <div class="form-group">
                  <label>优先级 *</label>
                  <select
                    v-model="formData.priority"
                    class="form-select"
                    required
                  >
                    <option value="normal">普通</option>
                    <option value="urgent">紧急</option>
                  </select>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label>执行类型 *</label>
                  <select
                    v-model="formData.execute_type"
                    class="form-select"
                    required
                    @change="onExecuteTypeChange"
                  >
                    <option value="immediate">立即执行</option>
                    <option value="scheduled">定时执行</option>
                    <option value="manual">手动启动</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>负责人</label>
                  <select
                    v-model="formData.responsible_person_id"
                    class="form-select"
                  >
                    <option value="">请选择负责人</option>
                    <option
                      v-for="user in users"
                      :key="user.id"
                      :value="user.id"
                    >
                      {{ user.username }}
                    </option>
                  </select>
                </div>
              </div>
              <div
                class="form-row"
                v-if="formData.execute_type === 'scheduled'"
              >
                <div class="form-group">
                  <label>计划执行时间 *</label>
                  <input
                    type="datetime-local"
                    v-model="formData.scheduled_time"
                    class="form-input"
                    required
                  />
                </div>
              </div>

              <div class="form-group">
                <label>任务描述</label>
                <textarea
                  v-model="formData.description"
                  class="form-textarea"
                  rows="3"
                  placeholder="请输入任务描述"
                ></textarea>
              </div>
            </div>

            <!-- 关联配置 -->
            <div class="form-section">
              <h3>关联配置</h3>

              <div class="form-group">
                <label>绑定航线 * (只能选择一个航线)</label>
                <div class="route-selector">
                  <div class="available-routes">
                    <h4>可用航线</h4>
                    <div
                      v-for="route in availableRoutes"
                      :key="route.id"
                      class="route-item"
                      :class="{
                        'selected-option': selectedRoutes.find(
                          (r) => r.id === route.id
                        ),
                      }"
                      @click="addRoute(route)"
                    >
                      {{ route.name }}
                    </div>
                  </div>
                  <div class="selected-routes">
                    <h4>已选航线</h4>
                    <div
                      v-for="(route, index) in selectedRoutes"
                      :key="route.id"
                      class="route-item selected"
                      draggable="true"
                      @dragstart="dragStart(index)"
                      @dragover.prevent
                      @drop="drop($event, index)"
                      style="cursor: pointer"
                      @dblclick="editRoute(route.id)"
                      title="双击编辑航线"
                    >
                      <span class="order-number">{{ index + 1 }}</span>
                      {{ route.name }}
                      <button
                        type="button"
                        class="remove-btn"
                        @click="removeRoute(index)"
                      >
                        &times;
                      </button>
                    </div>
                    <p v-if="selectedRoutes.length === 0" class="empty-text">
                      请选择航线
                    </p>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label>选择无人机 (可选，只能选择一个无人机)</label>
                <div class="route-selector">
                  <div class="available-routes">
                    <h4>可用无人机</h4>
                    <div
                      v-for="drone in availableDrones"
                      :key="drone.id"
                      class="route-item"
                      :class="{
                        'selected-option': isDroneSelected(drone.id),
                      }"
                      @click="addDrone(drone)"
                    >
                      {{ drone.name }}
                    </div>
                    <p v-if="availableDrones.length === 0" class="empty-text">
                      暂无可用无人机
                    </p>
                  </div>
                  <div class="selected-routes">
                    <h4>已选无人机</h4>
                    <div
                      v-for="(drone, index) in selectedDrones"
                      :key="drone.id"
                      class="route-item selected"
                    >
                      {{ drone.name }}
                      <button
                        type="button"
                        class="remove-btn"
                        @click="removeDrone(index)"
                      >
                        &times;
                      </button>
                    </div>
                    <p v-if="selectedDrones.length === 0" class="empty-text">
                      请选择无人机
                    </p>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <div class="model-selector">
                  <div class="available-models">
                    <h4>可用模型</h4>
                    <div
                      v-for="model in detectionModels"
                      :key="model.id"
                      class="model-item"
                      :class="{
                        selected: formData.detection_model_ids.includes(
                          model.id
                        ),
                      }"
                      @click="toggleModel(model.id)"
                    >
                      {{ model.name }}
                    </div>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label>触发条件</label>
                <div class="trigger-conditions">
                  <div
                    v-for="(condition, index) in formData.trigger_conditions"
                    :key="index"
                    class="condition-item"
                  >
                    <div class="condition-header">
                      <select
                        v-model="condition.type"
                        class="form-select small"
                      >
                        <option value="coordinate">到达指定坐标</option>
                        <option value="time">到达指定时间</option>
                        <option value="manual">手动触发</option>
                      </select>
                      <button
                        type="button"
                        class="remove-btn"
                        @click="removeTriggerCondition(index)"
                      >
                        &times;
                      </button>
                    </div>
                    <div class="condition-params">
                      <div v-if="condition.type === 'coordinate'">
                        <div class="form-row">
                          <div class="form-group">
                            <label>纬度</label>
                            <input
                              type="number"
                              v-model.number="condition.params.lat"
                              class="form-input"
                              step="0.000001"
                            />
                          </div>
                          <div class="form-group">
                            <label>经度</label>
                            <input
                              type="number"
                              v-model.number="condition.params.lng"
                              class="form-input"
                              step="0.000001"
                            />
                          </div>
                          <div class="form-group">
                            <label>半径(米)</label>
                            <input
                              type="number"
                              v-model.number="condition.params.radius"
                              class="form-input"
                              min="1"
                            />
                          </div>
                        </div>
                      </div>
                      <div v-else-if="condition.type === 'time'">
                        <input
                          type="datetime-local"
                          v-model="condition.params.time"
                          class="form-input"
                        />
                      </div>
                    </div>
                  </div>
                  <button
                    type="button"
                    class="btn btn-sm btn-secondary"
                    @click="addTriggerCondition"
                  >
                    添加触发条件
                  </button>
                </div>
              </div>
            </div>

            <!-- 异常策略 -->
            <div class="form-section">
              <h3>异常策略</h3>
              <div class="exception-strategies">
                <div
                  v-for="(strategy, index) in formData.exception_strategies"
                  :key="index"
                  class="strategy-item"
                >
                  <div class="strategy-header">
                    <select v-model="strategy.type" class="form-select small">
                      <option value="low_battery">低电量</option>
                      <option value="signal_loss">信号丢失</option>
                      <option value="detection_alert">检测到泄漏</option>
                    </select>
                    <select v-model="strategy.action" class="form-select small">
                      <option value="return_home">返航</option>
                      <option value="manual_takeover">人工接管</option>
                      <option value="mark_location">标记坐标并上传</option>
                    </select>
                    <button
                      type="button"
                      class="remove-btn"
                      @click="removeExceptionStrategy(index)"
                    >
                      &times;
                    </button>
                  </div>
                  <div class="strategy-params">
                    <div v-if="strategy.type === 'low_battery'">
                      <div class="form-group">
                        <label>电量阈值(%)</label>
                        <input
                          type="number"
                          v-model.number="strategy.params.battery_threshold"
                          class="form-input"
                          min="1"
                          max="100"
                        />
                      </div>
                    </div>
                    <div v-if="strategy.action === 'mark_location'">
                      <div class="form-group">
                        <label>上传间隔(秒)</label>
                        <input
                          type="number"
                          v-model.number="strategy.params.upload_interval"
                          class="form-input"
                          min="1"
                        />
                      </div>
                    </div>
                  </div>
                </div>
                <button
                  type="button"
                  class="btn btn-sm btn-secondary"
                  @click="addExceptionStrategy"
                >
                  添加异常策略
                </button>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div class="form-actions">
              <button
                type="button"
                class="btn btn-secondary"
                @click="closeDialog"
              >
                取消
              </button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.route-item.selected-option {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
}
</style>

<script>
import taskApi from "@/api/modules/task";
import { userService } from "@/api/modules/user";
import { flightRouteService } from "@/api/modules/flightRoute";
import { detectionModelService } from "@/api/modules/detectionModel";
import { droneService } from "@/api";

export default {
  name: "Tasks",
  data() {
    return {
      // 任务列表相关
      tasks: [],
      page: 1,
      pageSize: 10,
      total: 0,
      searchKeyword: "",
      filterStatus: "",
      filterPriority: "",

      // 对话框状态
      showDialog: false,
      showDetailDialog: false,
      isEditMode: false,
      currentTask: null,

      // 表单数据
      formData: {
        name: "",
        description: "",
        priority: "normal",
        execute_type: "immediate",
        scheduled_time: "",
        responsible_person_id: null,
        drone_ids: [],
        detection_model_ids: [],
        trigger_conditions: [],
        exception_strategies: [],
      },

      // 关联数据
      users: [],
      availableRoutes: [],
      selectedRoutes: [],
      detectionModels: [],
      availableDrones: [],
      selectedDrones: [],

      // 拖拽相关
      draggedIndex: null,
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    sortedTaskRoutes() {
      if (!this.currentTask || !this.currentTask.task_routes) return [];
      return [...this.currentTask.task_routes].sort(
        (a, b) => a.order_index - b.order_index
      );
    },
  },
  created() {
    // 导入Vue Router
    this.router = this.$router;
  },
  mounted() {
    this.getTasks();
    this.loadRelatedData();
  },
  methods: {
    // 获取任务列表
    async getTasks() {
      try {
        const params = {
          page: this.page,
          page_size: this.pageSize,
          keyword: this.searchKeyword,
          status: this.filterStatus,
          priority: this.filterPriority,
        };

        const response = await taskApi.getTasks(params);
        this.tasks = response.items || [];
        this.total = response.total || 0;
      } catch (error) {
        this.$message.error(
          "获取任务列表失败：" + (error.message || "未知错误")
        );
      }
    },

    // 加载关联数据
    async loadRelatedData() {
      try {
        // 加载用户列表
        const usersResponse = await userService.getUsers({
          page: 1,
          page_size: 100,
        });
        this.users = usersResponse.data.items || [];
        
        // 加载航线列表
        const routesResponse = await flightRouteService.getRoutes({
          page: 1,
          page_size: 100,
        });
        this.availableRoutes = routesResponse.items || [];

        // 加载检测模型列表
        const modelsResponse = await detectionModelService.getDetectionModels({
          page: 1,
          page_size: 100,
        });
        this.detectionModels = modelsResponse.items || [];
        
        // 加载无人机列表
        try {
          const dronesResponse = await droneService.getDrones({
            page: 1,
            page_size: 100,
          });
          this.availableDrones = dronesResponse.data.items || [];
        } catch (droneError) {
          console.error("加载无人机列表失败:", droneError);
          // 如果无人机服务调用失败，不影响其他功能
          this.availableDrones = [];
        }
      } catch (error) {
        console.error("加载关联数据失败:", error);
      }
    },

    // 分页切换
    changePage(newPage) {
      if (newPage >= 1 && newPage <= this.totalPages) {
        this.page = newPage;
        this.getTasks();
      }
    },

    // 打开创建对话框
    openCreateDialog() {
      this.isEditMode = false;
      this.resetForm();
      this.showDialog = true;
    },

    // 编辑任务
    editTask(task) {
      this.isEditMode = true;
      this.currentTask = task;
      this.formData = {
        name: task.name,
        description: task.description || "",
        priority: task.priority,
        execute_type: task.execute_type,
        scheduled_time: task.scheduled_time
          ? this.formatDateTimeForInput(task.scheduled_time)
          : "",
        responsible_person_id: task.responsible_person_id || null,
        drone_ids: task.drone_ids || [],
        detection_model_ids: task.detection_model_ids || [],
        trigger_conditions: JSON.parse(
          JSON.stringify(task.trigger_conditions || [])
        ),
        exception_strategies: JSON.parse(
          JSON.stringify(task.exception_strategies || [])
        ),
      };

      // 加载已选航线
      this.selectedRoutes = [];
      if (task.task_routes) {
        const sortedRoutes = [...task.task_routes].sort(
          (a, b) => a.order_index - b.order_index
        );
        sortedRoutes.forEach((taskRoute) => {
          if (taskRoute.route) {
            this.selectedRoutes.push({
              id: taskRoute.route.id,
              name: taskRoute.route.name,
            });
          }
        });
      }

      // 加载已选无人机
      this.selectedDrones = [];
      if (task.task_drones) {
        task.task_drones.forEach((taskDrone) => {
          if (taskDrone.drone) {
            this.selectedDrones.push({
              id: taskDrone.drone.id,
              name: taskDrone.drone.name,
            });
          }
        });
      }

      this.showDialog = true;
    },

    // 重置表单
    resetForm() {
      this.formData = {
        name: "",
        description: "",
        priority: "normal",
        execute_type: "immediate",
        scheduled_time: "",
        responsible_person_id: null,
        drone_ids: [],
        detection_model_ids: [],
        trigger_conditions: [],
        exception_strategies: [],
      };
      this.selectedRoutes = [];
      this.selectedDrones = [];
    },

    // 关闭对话框
    closeDialog() {
      this.showDialog = false;
      this.resetForm();
    },

    // 提交任务
    async submitTask() {
      try {
        // 验证航线
        if (this.selectedRoutes.length === 0) {
          this.$message.warning("请至少选择一条航线");
          return;
        }

        // 准备提交数据
        const submitData = {
          ...this.formData,
          route_ids: this.selectedRoutes.map((route) => route.id),
          route_order: this.selectedRoutes.map((_, index) => index),
          drone_ids: this.selectedDrones.map((drone) => drone.id),
        };

        // 如果是立即执行或手动启动，移除scheduled_time字段以避免后端解析错误
        if (
          this.formData.execute_type === "immediate" ||
          this.formData.execute_type === "manual"
        ) {
          delete submitData.scheduled_time;
        }

        // 手动启动任务设置为pending状态
        if (this.formData.execute_type === "manual") {
          submitData.status = "pending";
        }

        let response;
        if (this.isEditMode) {
          response = await taskApi.updateTask(this.currentTask.id, submitData);
          this.$message.success("任务更新成功");
        } else {
          response = await taskApi.createTask(submitData);
          this.$message.success("任务创建成功");
        }

        this.closeDialog();
        this.getTasks();
      } catch (error) {
        this.$message.error("操作失败：" + (error.message || "未知错误"));
      }
    },

    // 查看任务详情
    async viewTask(taskId) {
      try {
        const response = await taskApi.getTaskDetail(taskId);
        this.currentTask = response;
        this.showDetailDialog = true;
      } catch (error) {
        this.$message.error(
          "获取任务详情失败：" + (error.message || "未知错误")
        );
      }
    },

    // 删除任务
    async deleteTask(taskId) {
      if (confirm("确定要删除这个任务吗？")) {
        try {
          await taskApi.deleteTask(taskId);
          this.$message.success("任务删除成功");
          this.getTasks();
        } catch (error) {
          this.$message.error("删除失败：" + (error.message || "未知错误"));
        }
      }
    },

    // 更新任务状态
    async updateTaskStatus(taskId, status) {
      try {
        await taskApi.updateTaskStatus(taskId, { status });
        this.$message.success("任务状态更新成功");
        this.getTasks();
      } catch (error) {
        this.$message.error("状态更新失败：" + (error.message || "未知错误"));
      }
    },

    // 执行类型变更处理
    onExecuteTypeChange() {
      if (
        this.formData.execute_type === "immediate" ||
        this.formData.execute_type === "manual"
      ) {
        this.formData.scheduled_time = "";
      }
    },

    // 获取执行类型文本
    getExecuteTypeText(executeType) {
      const typeMap = {
        immediate: "立即执行",
        scheduled: "定时执行",
        manual: "手动启动",
      };
      return typeMap[executeType] || executeType;
    },

    // 添加航线
    addRoute(route) {
      // 清空已选列表，确保只能选择一个航线
      this.selectedRoutes = [
        {
          id: route.id,
          name: route.name,
        },
      ];
    },

    // 移除航线
    removeRoute(index) {
      this.selectedRoutes.splice(index, 1);
    },

    // 编辑航线
    editRoute(routeId) {
      // 跳转到航线编辑页面
      this.router.push({
        name: "FlightRoutes",
        query: { edit: "true", id: routeId },
      });
    },

    // 切换模型选择
    toggleModel(modelId) {
      const index = this.formData.detection_model_ids.indexOf(modelId);
      if (index > -1) {
        this.formData.detection_model_ids.splice(index, 1);
      } else {
        this.formData.detection_model_ids.push(modelId);
      }
    },

    // 添加无人机
    addDrone(drone) {
      // 清空已选列表，确保只能选择一个无人机
      this.selectedDrones = [
        {
          id: drone.id,
          name: drone.name,
        },
      ];
    },

    // 移除无人机
    removeDrone(index) {
      this.selectedDrones.splice(index, 1);
    },

    // 检查无人机是否已选中
    isDroneSelected(droneId) {
      return this.selectedDrones.some(drone => drone.id === droneId);
    },

    // 添加触发条件
    addTriggerCondition() {
      this.formData.trigger_conditions.push({
        type: "manual",
        params: {},
      });
    },

    // 移除触发条件
    removeTriggerCondition(index) {
      this.formData.trigger_conditions.splice(index, 1);
    },

    // 添加异常策略
    addExceptionStrategy() {
      this.formData.exception_strategies.push({
        type: "low_battery",
        action: "return_home",
        params: {
          battery_threshold: 20,
        },
      });
    },

    // 移除异常策略
    removeExceptionStrategy(index) {
      this.formData.exception_strategies.splice(index, 1);
    },

    // 拖拽开始
    dragStart(index) {
      this.draggedIndex = index;
    },

    // 拖拽悬停
    dragOver(event, index) {
      event.preventDefault();
    },

    // 拖拽放置
    drop(event, index) {
      event.preventDefault();
      if (this.draggedIndex !== null && this.draggedIndex !== index) {
        const item = this.selectedRoutes[this.draggedIndex];
        this.selectedRoutes.splice(this.draggedIndex, 1);
        this.selectedRoutes.splice(index, 0, item);
        this.draggedIndex = null;
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
    },

    // 格式化日期时间用于输入框
    formatDateTimeForInput(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return date.toISOString().slice(0, 16);
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        draft: "草稿",
        scheduled: "已计划",
        pending: "待启动",
        in_progress: "进行中",
        paused: "已暂停",
        completed: "已完成",
        cancelled: "已取消",
        failed: "已失败",
      };
      return statusMap[status] || status;
    },

    // 获取触发类型文本
    getTriggerTypeText(type) {
      const typeMap = {
        coordinate: "到达指定坐标",
        time: "到达指定时间",
        manual: "手动触发",
      };
      return typeMap[type] || type;
    },

    // 格式化触发参数
    formatTriggerParams(condition) {
      if (condition.type === "coordinate") {
        const { lat, lng, radius } = condition.params || {};
        return `${lat || 0}, ${lng || 0} (半径: ${radius || 0}m)`;
      } else if (condition.type === "time") {
        return this.formatDate(condition.params?.time);
      }
      return "";
    },

    // 获取异常类型文本
    getExceptionTypeText(type) {
      const typeMap = {
        low_battery: "低电量",
        signal_loss: "信号丢失",
        detection_alert: "检测到泄漏",
      };
      return typeMap[type] || type;
    },

    // 获取动作文本
    getActionText(action) {
      const actionMap = {
        return_home: "返航",
        manual_takeover: "人工接管",
        mark_location: "标记坐标并上传",
      };
      return actionMap[action] || action;
    },

    // 格式化参数键名
    formatParamKey(key) {
      const keyMap = {
        battery_threshold: "电量阈值",
        upload_interval: "上传间隔",
      };
      return keyMap[key] || key;
    },
  },
};
</script>

<style scoped>
.task-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #1f2937;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.search-filter {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.task-list {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.priority-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.priority-tag.normal {
  background-color: #dbeafe;
  color: #1e40af;
}

.priority-tag.urgent {
  background-color: #fee2e2;
  color: #991b1b;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.draft {
  background-color: #f3f4f6;
  color: #6b7280;
}

.status-tag.scheduled {
  background-color: #dbeafe;
  color: #1e40af;
}

.status-tag.in_progress {
  background-color: #dcfce7;
  color: #166534;
}

.status-tag.paused {
  background-color: #fef3c7;
  color: #92400e;
}

.status-tag.completed {
  background-color: #e0f2fe;
  color: #0c4a6e;
}

.status-tag.cancelled {
  background-color: #f3f4f6;
  color: #6b7280;
}

.status-tag.failed {
  background-color: #fee2e2;
  color: #991b1b;
}

.progress-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-bar {
  flex: 1;
  height: 8px;
  background-color: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #10b981;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #6b7280;
  min-width: 35px;
  text-align: right;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12px;
  padding: 16px 0;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  background-color: #6b7280;
  color: white;
}

.btn-secondary:hover {
  background-color: #4b5563;
}

.btn-success {
  background-color: #10b981;
  color: white;
}

.btn-success:hover {
  background-color: #059669;
}

.btn-danger {
  background-color: #ef4444;
  color: white;
}

.btn-danger:hover {
  background-color: #dc2626;
}

.btn-warning {
  background-color: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background-color: #d97706;
}

.btn-info {
  background-color: #06b6d4;
  color: white;
}

.btn-info:hover {
  background-color: #0891b2;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
  margin-right: 4px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 对话框样式 */
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  height: 500px;
  overflow-y: scroll;
}

/* 详情页面样式 */
.detail-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.detail-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  color: #1f2937;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.subsection {
  margin-bottom: 16px;
  padding: 12px;
  background-color: white;
  border-radius: 6px;
}

.subsection h4 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 16px;
  color: #374151;
}

.mini-table {
  width: 100%;
  border-collapse: collapse;
}

.mini-table th,
.mini-table td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
}

.model-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.model-tag {
  padding: 4px 8px;
  background-color: #dbeafe;
  color: #1e40af;
  border-radius: 4px;
  font-size: 12px;
}

.condition-item,
.strategy-item {
  margin-bottom: 12px;
  padding: 12px;
  background-color: white;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
}

.strategy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.strategy-action {
  padding: 2px 6px;
  background-color: #dcfce7;
  color: #166534;
  border-radius: 3px;
  font-size: 12px;
}

.strategy-params,
.condition-params {
  margin-top: 8px;
  padding: 8px;
  background-color: #f9fafb;
  border-radius: 4px;
}

.param-item {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
}

/* 表单样式 */
.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9fafb;
  border-radius: 8px;
}

.form-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  color: #1f2937;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-weight: 500;
  color: #374151;
}

.form-input,
.form-select,
.form-textarea {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-select.small {
  width: auto;
  min-width: 150px;
}

/* 航线选择器 */
.route-selector {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.available-routes,
.selected-routes {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.available-routes h4,
.selected-routes h4,
.available-models h4 {
  margin: 0;
  font-size: 16px;
  color: #374151;
}

.route-item {
  padding: 12px;
  background-color: white;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.route-item:hover {
  border-color: #3b82f6;
  background-color: #f0f9ff;
}

.route-item.selected {
  border-color: #10b981;
  background-color: #dcfce7;
  position: relative;
}

.order-number {
  margin-right: 8px;
  font-weight: 600;
  color: #166534;
}

.remove-btn {
  background: none;
  border: none;
  color: #ef4444;
  cursor: pointer;
  font-size: 16px;
}

.empty-text {
  text-align: center;
  color: #6b7280;
  font-style: italic;
}

/* 模型选择器 */
.model-selector {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.available-models {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.model-item {
  padding: 8px 12px;
  background-color: white;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-block;
  margin-right: 8px;
  margin-bottom: 8px;
}

.model-item:hover {
  border-color: #3b82f6;
  background-color: #f0f9ff;
}

.model-item.selected {
  border-color: #10b981;
  background-color: #dcfce7;
}

/* 触发条件和异常策略 */
.trigger-conditions,
.exception-strategies {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.condition-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}
</style>
